package com.onefive.android.ui;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.google.ads.AdRequest;
import com.google.ads.AdSize;
import com.google.ads.AdView;
import com.onefive.android.R;
import com.onefive.android.adapter.YtubeAdapter;
import com.onefive.android.db.YtubeColumns;
import com.onefive.android.db.YtubeQuery;
import com.onefive.android.model.YouTubeObject;
import com.onefive.android.service.UpdateService;
import com.onefive.android.utils.Config;
import com.onefive.android.utils.DetachableResultReceiver;
import com.onefive.android.utils.DetachableResultReceiver.Receiver;
import com.onefive.android.utils.YtubeProcessor;

public class YoutubeActivity extends GAActivity implements Receiver, LoaderManager.LoaderCallbacks<Cursor>, OnItemClickListener, OnScrollListener,
		OnClickListener {

	private DetachableResultReceiver receiver;
	private ProgressDialog progress;
	private ListView listView;
	private static final String SHOW_PROGRESS = "show_progress";
	private YtubeAdapter adapter;
	private Button button;
	public static final String ADS_ID = "a14f2ba088a91a0";
	private static int limit = Config.step_limit;
	private Cursor mCursor;
	private boolean visibility = true;
	private static final String RU = "AdamThomasMoran";
	private static final String US = "plus100500eng";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		listView = (ListView) findViewById(R.id.list);
		button = (Button) findViewById(R.id.show_more);
		button.setOnClickListener(this);

		listView.setOnItemClickListener(this);
		listView.setOnScrollListener(this);

		receiver = new DetachableResultReceiver(new Handler());
		receiver.setReceiver(this);

		updateList(1, 2 * Config.step_limit);

		Bundle bundle = new Bundle();
		bundle.putBoolean(SHOW_PROGRESS, true);
		bundle.putString(Config.TYPE, US);
		getSupportLoaderManager().initLoader(YtubeQuery._TOKEN, bundle, this);

		LinearLayout layout = (LinearLayout) findViewById(R.id.ads);
		AdView adView = new AdView(this, AdSize.BANNER, ADS_ID);
		layout.addView(adView);
		AdRequest request = new AdRequest();
		// request.setTesting(true);
		adView.loadAd(request);

	}

	private void updateList(int start, int count) {
		Intent upfateIntent = new Intent(Intent.ACTION_SYNC, null, this, UpdateService.class);
		upfateIntent.putExtra(UpdateService.EXTRA_STATUS_RECEIVER, receiver);
		upfateIntent.putExtra(UpdateService.EXTRA_REQUEST_CODE, Config.YTUBE);
		upfateIntent.putExtra(Config.TYPE, US);
		upfateIntent.putExtra(Config.START, start);
		upfateIntent.putExtra(Config.COUNT, count);
		startService(upfateIntent);
	}

	@Override
	protected void onDestroy() {
		limit = Config.step_limit;
		super.onDestroy();
	}

	@Override
	public void onReceiveResult(int resultCode, Bundle resultData) {
		switch (resultCode) {
		case UpdateService.STATUS_RUNNING:
			break;
		case UpdateService.STATUS_ERROR:
			break;
		case UpdateService.STATUS_FINISHED:
			Bundle bundle = new Bundle();
			bundle.putBoolean(SHOW_PROGRESS, false);
			// getSupportLoaderManager().restartLoader(YtubeQuery._TOKEN,
			// bundle, this);
			bundle.putString(Config.TYPE, US);
			getSupportLoaderManager().destroyLoader(YtubeQuery._TOKEN);
			getSupportLoaderManager().initLoader(YtubeQuery._TOKEN, bundle, this);
		}

	}

	@Override
	public Loader<Cursor> onCreateLoader(int id, Bundle bundle) {
		switch (id) {
		case YtubeQuery._TOKEN:
			if (bundle.getBoolean(SHOW_PROGRESS))
				progress = ProgressDialog.show(this, getString(R.string.loading), getString(R.string.please_wait), true, false);
			String type = bundle.getString(Config.TYPE);
			return new CursorLoader(YoutubeActivity.this, YouTubeObject.CONTENT_URI, YtubeQuery.PROJECTION, YtubeColumns.TYPE.getName() + "=?",
					new String[] { type }, YouTubeObject.DATE_SORT + " limit " + limit);
		default:
			return null;
		}

	}

	@Override
	public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
		switch (loader.getId()) {
		case YtubeQuery._TOKEN:
			if (progress != null)
				progress.dismiss();
			startManagingCursor(cursor);
			mCursor = cursor;
			if (adapter == null) {
				adapter = new YtubeAdapter(YoutubeActivity.this, cursor);
				listView.setAdapter(adapter);
			} else {
				adapter.changeCursor(cursor);
				adapter.notifyDataSetChanged();
			}
			break;
		default:
			break;
		}

	}

	@Override
	public void onLoaderReset(Loader<Cursor> arg0) {

	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
		if (mCursor != null && mCursor.moveToPosition(position)) {
			String idVideo = mCursor.getString(YtubeQuery._ID);

			try {
				Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + idVideo));
				startActivity(intent);
			} catch (Exception e) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setData(Uri.parse("market://search?q=pname:com.google.android.youtube"));
				try {
					startActivity(intent);
				} catch (Exception e2) {
					e2.printStackTrace();
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.show_more:

//			button.setVisibility(View.GONE);
//			limit += Config.step_limit;
//			if (limit > YtubeProcessor.total) {
//				visibility = false;
//			} else {
//				updateList(limit, Config.step_limit);
//			}
//			Bundle bundle = new Bundle();
//			bundle.putBoolean(SHOW_PROGRESS, false);
//			//TODO
//			getSupportLoaderManager().restartLoader(YtubeQuery._TOKEN, bundle, this);
//			break;

		default:
			break;
		}
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
		button.setVisibility((visibility && totalItemCount - firstVisibleItem < 3) ? View.VISIBLE : View.GONE);
	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
	}

}